package org.lennon.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.lennon.log.dao.LogMapper;
import org.lennon.log.model.LogModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("parseLog")
public class ParseLog {
	private static final int ELENUM = 11;

	@Autowired
	private LogMapper mapper;

	public void saveLogFileHistory(String fileName){
		mapper.saveLogFileHistory(fileName);
	}
	
	public List<Map<String, Integer>> getLineData(String project, String date) {

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
		long beginDate = 0;
		try {
			beginDate = (simpleDateFormat.parse(date).getTime() / 1000);
			return mapper.getLineData(project, beginDate, (86399 + beginDate));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

	public List<Map<String, Integer>> getReqMethodData(String project, String date) {

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
		long beginDate = 0;
		try {
			beginDate = (simpleDateFormat.parse(date).getTime() / 1000);
			return mapper.getReqMethodData(project, beginDate, (86399 + beginDate));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

	public List<Map<String, Integer>> getReqResultData(String project, String date) {

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
		long beginDate = 0;
		try {
			beginDate = (simpleDateFormat.parse(date).getTime() / 1000);
			return mapper.getReqResultData(project, beginDate, (86399 + beginDate));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

	public List<Map<String, Integer>> getReqTypeData(String project, String date) {

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
		long beginDate = 0;
		try {
			beginDate = (simpleDateFormat.parse(date).getTime() / 1000);
			return mapper.getReqTypeData(project, beginDate, (86399 + beginDate));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}
	
	public List<Map<String,Integer>> getTopVisit(String project,int number){
		return mapper.getTopVisit(project, number);
	}
	public List<Map<String,Integer>> getTopBytes(String project,int number){
		return mapper.getTopBytes(project, number);
	}
	public List<Map<String,Object>> getTopPage(String project,int number){
		return mapper.getTopPage(project, number);
	}
	public List<Map<String,Object>> getTopSlowPage(String project,int number){
		return mapper.getTopSlowPage(project, number);
	}

	public List<String> getProjectList() {
		return mapper.getProjectList();
	}

	public void loadFromFile(final String project, final String path) {
		readFile(path, line -> {
			String pro = " ";
			String elements[] = line.split(" ");
			LogModel model = new LogModel();
			if (elements.length != ELENUM)
				return;
			model.setIp(elements[0]);
			model.setL_user(elements[1]);
			model.setU_user(elements[2]);
			SimpleDateFormat sdf = new SimpleDateFormat("dd/MMM/yyy:HH:mm:ss", Locale.US);
			Date date = null;
			try {
				date = sdf.parse(elements[3].substring(1));
			} catch (ParseException e) {
				e.printStackTrace();
			}

			model.setTime(new java.sql.Date(date.getTime()));
			model.setReqMethod(elements[5].substring(1));
			model.setReqUrl(elements[6]);
			int startIndex = elements[6].indexOf('/');
			int endIndex = elements[6].indexOf('/', 1);
			if (startIndex >= 0 && endIndex >= 0)
				pro = elements[6].substring(startIndex + 1, endIndex);
			model.setReqStyle(elements[7].substring(0, elements[7].length() - 1));
			model.setStatuscode(Integer.parseInt(elements[8]));
			try {
				model.setSentedbytes(Integer.parseInt(elements[9]));
			} catch (NumberFormatException e) {
				model.setSentedbytes(0);
			}

			model.setTimetaken(Float.parseFloat(elements[10]));
			if (null == pro) {
				pro = " ";
			}
			model.setProject(pro);
			try {
				mapper.saveLog(model);
			} catch (Exception e) {
				e.printStackTrace();
			}

		});

	}

	/**
	 * 功能：Java读取txt文件的内容 步骤：1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
	 * 3：读取到输入流后，需要读取生成字节流 4：一行一行的输出。readline()。 备注：需要考虑的是异常情况
	 * 
	 * @param filePath
	 */
	public static void readFile(final String filePath, readCallBack callback) {

		String encoding = "UTF-8";
		File file = new File(filePath);
		if (file.isFile() && file.exists()) { // 判断文件是否存在

			try {
				InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					// System.out.println(lineTxt);
					if (callback != null) {
						callback.onRead(lineTxt);
					}
				}
				read.close();
			} catch (Exception e) {
				System.out.println("读取文件内容出错");
				e.printStackTrace();
			} finally {
			}
		} else {
			System.out.println("找不到指定的文件");
		}

	}

	private static interface readCallBack {
		public void onRead(String line);
	}

	public static void main(String[] args) {
		// SimpleDateFormat sdf = new SimpleDateFormat("dd/MMM/yyyy");
		// Date d = null;
		// try {
		// d = sdf.parse("22/Dec/2016");
		// } catch (ParseException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// System.out.println(d);

		// String stringDate = "22/Dec/2016:04:13:46";
		// SimpleDateFormat sdf = new
		// SimpleDateFormat("dd/MMM/yyy:HH:mm:ss",Locale.US);
		// Date date = null;
		// try {
		// date = sdf.parse(stringDate);
		// } catch (ParseException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// // System.out.println(date.toString());
		// sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// System.out.println(sdf.format(date));

		// String line = "127.224.108.249 - - [22/Dec/2016:04:13:46 +0800]
		// \"POST /punch/diary/uploadFile HTTP/1.1\" 200 138 0.1";
		// String elements[] = line.split(" ");
		// LogModel model = new LogModel();
		// if (elements.length != ELENUM)
		// return;
		// model.setIp(elements[0]);
		// model.setL_user(elements[1]);
		// model.setU_user(elements[2]);
		// SimpleDateFormat sdf = new SimpleDateFormat("dd/MMM/yyy:HH:mm:ss",
		// Locale.US);
		// Date date = null;
		// try {
		// date = sdf.parse(elements[3].substring(1));
		// } catch (ParseException e) {
		// e.printStackTrace();
		// }
		//
		// model.setTime(new java.sql.Date(date.getTime()));
		// model.setReqMethod(elements[5].substring(1));
		// model.setReqUrl(elements[6]);
		// model.setReqStyle(elements[7].substring(0, elements[7].length() -
		// 1));
		// model.setStatuscode(Integer.parseInt(elements[8]));
		// model.setSentedbytes(Integer.parseInt(elements[9]));

//		Date date = new Date();
//		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH");
//
//		try {
//			Long stampTime = (simpleDateFormat.parse(simpleDateFormat.format(date)).getTime() / 1000);
//			Long timeLevel = (simpleDateFormat2.parse(simpleDateFormat2.format(date)).getTime() / 1000);
//		} catch (ParseException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}

	}
}
